package com.atguigu.gulimall.gulimallauthserver.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.gulimallauthserver.feign.MemberFeignService;
import com.atguigu.gulimall.gulimallauthserver.feign.ThirdPartFeignService;
import com.atguigu.gulimall.gulimallauthserver.vo.UserLoginVo;
import com.atguigu.gulimall.gulimallauthserver.vo.UserRegistVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 登录Controller
 *
 * @author xiaoping
 * @create 2020/6/29 19:50
 * @since 1.0.0
 */
@Slf4j
@Controller
public class LoginController {

    @Autowired
    ThirdPartFeignService thirdPartFeignService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    MemberFeignService memberFeignService;

    /**
     * 发送短信验证码
    * @param phone
     * @return
     */
    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendCode(@RequestParam("phone") String phone){

        //TODO 接口防刷

        String redisCode= redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(redisCode)){
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - l < 60000){
                //60秒内不能再发
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(),BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        //验证码的再次校验 redis , key-phone value-code sms:code:15574344957 -> 45678
        String code = UUID.randomUUID().toString().substring(0, 5);
        String s = code + "_" + System.currentTimeMillis();
        //redis缓存验证码，十分钟有效，防止同一个phone在60秒内再次发送验证码
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone,s,10, TimeUnit.MINUTES);

     thirdPartFeignService.sendCode(phone, code);
        return R.ok();
    }

    /**
     * 登录
     * @return
     */
    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session){
        try {
            //远程登录
            R r = memberFeignService.login(vo);
            if (r.getCode() == 0){
                //成功
                MemberRespVo data = r.getData("data", new TypeReference<MemberRespVo>() {});
                session.setAttribute(AuthServerConstant.LOGIN_USER, data);
                return "redirect:http://gulimall.com";
            }
            return errorRedirect(redirectAttributes,"msg",r.getData("msg",new TypeReference<String>(){}),"login");
        }catch (Exception e){
            e.printStackTrace();
            log.error("登录超时，请重新登录!");
            return errorRedirect(redirectAttributes,"msg","登录超时，请重新登录!","login");
        }
    }

    /**
     * 逻辑处理登录
     */
    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (attribute == null){
            //没登录
            return "login";
        }
        return "redirect:http://gulimall.com";
    }


    /**
     * 注册
     * @param vo                    注册信息
     * @param result               校验结果
     * @param redirectAttributes  重定向携带数据
     * @return
     */
    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo vo, BindingResult result, RedirectAttributes redirectAttributes){
        //注册成功回到首页，回到登录页
        try {
            if (result.hasErrors()){
                Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage,(s,a) -> s+","+a ));
                redirectAttributes.addFlashAttribute("errors",errors);
                //校验出错，转发到注册页
                return "redirect:http://auth.gulimall.com/reg.html";
            }
            //检验验证码
            String code = vo.getCode();
            String s = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
            if (!StringUtils.isEmpty(s)){
                if (code.equals(s.split("_")[0])){
                    //删除验证码，令牌机制
                    redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
                    //远程注册服务
                    R r = memberFeignService.regist(vo);
                    if (r.getCode() == 0){
                        //成功
                        return "redirect:http://auth.gulimall.com/login.html";
                    }else {
                        errorRedirect(redirectAttributes,"msg",r.getData("msg",new TypeReference<String>(){}),"reg");
                    }
                }else {
                    return errorRedirect(redirectAttributes,"code","验证码错误","reg");
                }
            }else {
                return errorRedirect(redirectAttributes,"code","验证码错误","reg");
            }
            return "redirect:http://auth.gulimall.com/login.html";
        }catch (Exception e){
            e.printStackTrace();
            return "redirect:http://auth.gulimall.com/reg.html";
        }
    }


    /**
     * 出错重定向注册页面
     * @param redirectAttributes        错误map
     * @param key                       错误key
     * @param val                       错误value
     * @param type                      跳转页面名称
     * @return
     */
    private String errorRedirect(RedirectAttributes redirectAttributes,String key,String val,String type) {
        Map<String, String> errors = new HashMap<>();
        errors.put(key, val);
        redirectAttributes.addFlashAttribute("errors", errors);
        return "redirect:http://auth.gulimall.com/"+type+".html";
    }


}
